package com.irdstudio.efp.esb.api.rest.zzd;


import java.util.Objects;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.irdstudio.efp.ctr.service.facade.CtrLoanContService;
import com.irdstudio.efp.ctr.service.vo.CtrLoanContVO;
import com.irdstudio.efp.esb.api.bean.zzd.ReqQryRepayAmtBean;
import com.irdstudio.efp.esb.api.bean.zzd.ResQryRepayAmtBean;
import com.irdstudio.efp.esb.api.rest.EsbServerController;
import com.irdstudio.efp.esb.common.constant.EsbBizEnums;
import com.irdstudio.efp.esb.service.bo.req.RepaymentLoanReq;
import com.irdstudio.efp.esb.service.bo.resp.RepaymentLoanResp;
import com.irdstudio.efp.esb.service.facade.RepaymentLoanService;
import com.irdstudio.basic.framework.core.exception.ESBException;
import com.irdstudio.basic.framework.core.util.InterfaceCheckUtils;
import com.irdstudio.basic.framework.core.util.StringUtil;

/**
 * 查询用户还款金额接口controller
 * @author qiuyf
 * @since 2018年12月18日 下午9:03:13
 * @version 1.0
 */
public class LoanQueryRepayAmountController implements EsbServerController {


	/**
	 * 日志记录变量
	 */
	private static Logger logger = LoggerFactory.getLogger(LoanQueryRepayAmountController.class);
	
	@Autowired
	@Qualifier("ctrLoanContService")
	private CtrLoanContService ctrLoanContService;
	
	@Autowired
	@Qualifier("repaymentLoanService")
	private RepaymentLoanService repaymentLoanService;
	

	@Override
	public String execute(String esbReqBodyBean) throws ESBException, Exception {
		// 请求对象
		ReqQryRepayAmtBean reqQryRepayAmtBean = null;
		// 响应对象
		ResQryRepayAmtBean returnBean = new ResQryRepayAmtBean();
		
		String esbRespBodyBean = null;
		// 贷款合同VO
		CtrLoanContVO ctrLoanContVo = new CtrLoanContVO();
		CtrLoanContVO resultCLCVo = null;
		//贷后还款试算请求对象
		RepaymentLoanReq repaymentLoanReq = new RepaymentLoanReq();
		// 贷后还款试算响应对象
		RepaymentLoanResp repaymentLoanResp = null;
		
		try {
			// 1.将请求报文对象转成相应的json
			reqQryRepayAmtBean = JSONObject.parseObject(esbReqBodyBean, ReqQryRepayAmtBean.class);
			logger.info("根据理财订单号：" + reqQryRepayAmtBean.getApplSeq() + "查询用户还款金额交易开始---------------------------");
			
			// 2.必输项校验
			this.checkRequired(reqQryRepayAmtBean);

			// 3.调用合同信息查询，根据贷款订单号获取贷款合同号
			ctrLoanContVo.setLoanAccount(reqQryRepayAmtBean.getApplSeq());   // 贷款账号 = 贷款订单号
		    resultCLCVo = ctrLoanContService.queryByCondition(ctrLoanContVo);
		    
		    if(StringUtil.isNullorBank(resultCLCVo.getContNo())) {
		    	throw new Exception("根据贷款订单号："+ reqQryRepayAmtBean.getApplSeq() + "获取的贷款合同号为空！");
		    }
			// 4.调用对应中台服务处理:根据贷款合同号、回收类型默认为全部结清（周转贷默认为PO全部结清）调用贷后回收试算接口
		    repaymentLoanReq.setBaseAcctNo(resultCLCVo.getContNo());  // 贷款号 = 合同号
		    repaymentLoanReq.setReceiptType(EsbBizEnums.PayBackType.ZZD.VALUE); // 回收类型
		    
		    repaymentLoanResp = repaymentLoanService.repaymentLoanService(repaymentLoanReq);

			// 5.判断查询结果,封装返回数据
			if(Objects.nonNull(repaymentLoanResp)) {
				returnBean.setRetCode(EsbBizEnums.RetCodeEnum.SUCCESS.VALUE);
				returnBean.setProductCorpSpid(reqQryRepayAmtBean.getProductCorpSpid());
				returnBean.setUserId(reqQryRepayAmtBean.getUserId());
				returnBean.setApplSeq(reqQryRepayAmtBean.getApplSeq());
				returnBean.setLoanAmt(String.valueOf(repaymentLoanResp.getPepayAmt()));  //贷款本金 = 还款本金金额
				returnBean.setCurType(repaymentLoanResp.getAmtType());  //币种类型 = 金额类型
				//字段赋值 TODO
				returnBean.setLoanTime(""); //贷款时间
				returnBean.setRepayAmount(""); //还款金额
				returnBean.setRepayAmount(String.valueOf(repaymentLoanResp.getTotalAmt())); //还款金额 = 总金额
				returnBean.setRepayPrcpAmt(""); //还款本金金额
				returnBean.setRepayIntAmt(""); //还款利息金额
				returnBean.setStampDuty(""); //印花税
				returnBean.setRepayOdInt(""); //还款罚息
				returnBean.setExplain(""); //还款说明
			}else {
				returnBean.setRetCode(EsbBizEnums.RetCodeEnum.FAILURE.VALUE);
				returnBean.setRetMsg("根据贷款合同号：\"+ resultCLCVo.getContNo() + \"查询贷后还款试算结果为空！");
				//returnBean.setBankRetcode("");  //银行内部错误码
				//returnBean.setBankRetmsg("根据贷款合同号："+ resultCLCVo.getContNo() + "查询贷后还款试算结果为空！");   //银行内部错误原因
			}
			
			// 6.object转成JSON string
			esbRespBodyBean = JSON.toJSONString(returnBean);
			
			logger.info("根据理财订单号：" + reqQryRepayAmtBean.getApplSeq() + "查询用户还款金额交易结束.....................");
		} catch (ESBException e) {
			logger.error("调用查询用户还款金额接口出错，错误信息为："+e.getMessage());
		} catch (Exception e) {
			logger.error("调用查询用户还款金额接口出错，错误信息为："+e.getMessage());
		}
		
		return esbRespBodyBean;
	}


	/**
	 * 查询用户还款金额接口请求报文必输项校验
	 * @param reqQryRepayAmtBean
	 * @throws ESBException
	 * @author qiuyf
	 * @since 2018年12月19日 下午2:55:39
	 * @version 1.0
	 */
	private void checkRequired(ReqQryRepayAmtBean reqQryRepayAmtBean) throws ESBException {
		//协议参数
		InterfaceCheckUtils.getValue("signType", "签名方式", reqQryRepayAmtBean.getSignType(), true);
		InterfaceCheckUtils.getValue("serviceVersion", "接口版本", reqQryRepayAmtBean.getServiceVersion(), true);
		InterfaceCheckUtils.getValue("inputCharset", "字符集", reqQryRepayAmtBean.getInputCharset(), true);
		InterfaceCheckUtils.getValue("sign", "签名", reqQryRepayAmtBean.getSign(), true);
		InterfaceCheckUtils.getValue("signKeyIndex", "密钥序号", reqQryRepayAmtBean.getSignKeyIndex(), true);
		//业务参数
		InterfaceCheckUtils.getValue("productCorpSpid", "基金公司商户号", reqQryRepayAmtBean.getProductCorpSpid(), true);
		InterfaceCheckUtils.getValue("userId", "真身id", reqQryRepayAmtBean.getUserId(), true);
		InterfaceCheckUtils.getValue("applSeq", "贷款订单号", reqQryRepayAmtBean.getApplSeq(), true);
		InterfaceCheckUtils.getValue("loanAmt", "贷款本金", reqQryRepayAmtBean.getLoanAmt(), true);
		InterfaceCheckUtils.getValue("curType", "币种", reqQryRepayAmtBean.getCurType(), true);
		InterfaceCheckUtils.getValue("loanTime", "贷款时间", reqQryRepayAmtBean.getLoanTime(), true);
	}

}
